import 'dart:convert';

import 'package:flutter/material.dart';

import '../../api/DeviceApi.dart';
import '../../commponets/ItemView.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../tools/widgets/my_button.dart';
import '../../utils/toast_utils.dart';

class AddQrPage extends StatefulWidget {
  const AddQrPage({
    super.key,
    this.scanResult
  });

  final String? scanResult; // 新增：接收扫描结果

  @override
  State<AddQrPage> createState() => _AddQrPageState();
}

class _AddQrPageState extends State<AddQrPage> {
  final TextEditingController _codeController = TextEditingController();
  final DeviceApi _deviceApi = DeviceApi();
  late int _deviceId;
  String _scanData = "";
  String _deviceImage = "images/images/add/q1.png";
  String _deviceName = '添加设备信息'; // 默认为门铃名称
  String _statusText = '正在添加'; // 状态文本
  Widget? _statusIcon; // 状态图标
  bool _clickable = false;
  String _clickableData = '完成';

  // 表单数据和初始值
  final Map<String, dynamic> _formData = {
    'type': null,
    'device_id': '',
  };


  @override
  void initState() {
    super.initState();

    print('扫描成功2222，结果: $_scanData');

    // 检查是否有扫描结果传入
    if (widget.scanResult != null) {
      setState(() {
        _scanData = widget.scanResult!;
        _codeController.text = _scanData;

        // 解析JSON数据并提取type和sn
        try {
          final jsonData = json.decode(_scanData);
          if (jsonData is Map<String, dynamic>) {
            if (jsonData['type'] == null || jsonData['type'] == '' ||
                jsonData['device_id'] == null || jsonData['device_id'] == ''
            ) {
              Toast.show("扫描结果不是有效的JSON对象,请重新扫描");
              Future.delayed(const Duration(seconds: 2), () {
                if (mounted) {
                  Navigator.pushNamed(context, "/home");
                }
              });
            }


            _formData['type'] = jsonData['type'];
            _formData['device_id'] = jsonData['device_id'] ?? '';
            print('解析成功: type=${_formData['type']}, device_id=${_formData['device_id']}');

            // 根据type设置设备图片和名称
            _setDeviceInfoByType(_formData['type']);

            _fetchData();
          } else {
            Toast.show("扫描结果不是有效的JSON对象,请重新扫描");
            Future.delayed(const Duration(seconds: 2), () {
              if (mounted) {
                Navigator.pushNamed(context, "/home");
              }
            });
          }
        } catch (e) {
          Toast.show('JSON解析错误,请重新扫描');
          Future.delayed(const Duration(seconds: 2), () {
            if (mounted) {
              Navigator.pushNamed(context, "/home");
            }
          });
        }
      });
    }

  }

  Future<void> _fetchData() async {
    try {
      final response = await _deviceApi.addDevice(_formData).timeout(
        const Duration(seconds: 10),
      );

      if (response.code == 200) {
        print(response.data);
        Toast.show("添加设备成功");
        setState(() {
          _statusText = '添加成功';
          _clickable = true;
          _clickableData = '完成';
          _statusIcon = Image.asset(
            "images/images/add/d1.png",
            width: 20,
            height: 20,
            fit: BoxFit.contain,
          );
        });
      } else {
        Toast.show("添加失败，${response.getMsg}");
        setState(() {
          _statusText = '添加失败';
          _clickableData = '返回';
          _clickable = true;
          _statusIcon = Image.asset(
            "images/images/add/d2.png",
            width: 20,
            height: 20,
            fit: BoxFit.contain,
          );
        });
      }
    } catch (e) {
      Toast.show("请求失败");
      setState(() {
        _statusText = '添加失败';
        _clickableData = '返回';
        _clickable = true;
        _statusIcon = Image.asset(
          "images/images/add/d2.png",
          width: 20,
          height: 20,
          fit: BoxFit.contain,
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: '添加设备',
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Container(
                //设置ItemView离左右的距离
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: Column(
                  children: [
                    const SizedBox(height: 20),

                    ItemView(
                      width: 400,
                      height: 70,
                      leftPadding: 10,
                      rightPadding: 20,
                      leftWidget: Row(
                        children: [
                          Image.asset(
                            _deviceImage,
                            width: 40,
                            height: 40,
                            fit: BoxFit.contain,
                          ),
                          const SizedBox(width: 10),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const SizedBox(height: 12),
                              Text(
                                _deviceName,
                                style: const TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 5),
                              Text(
                                _statusText,
                                style: const TextStyle(
                                  fontSize: 12.0,
                                  color: Colors.black45,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      rightWidget: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _statusIcon ?? Container(
                            width: 30,
                            height: 30,
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                Container(
                                  width: 40,
                                  height: 40,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                                  ),
                                ),
                                Container(
                                  width: 10,
                                  height: 10,
                                  color: Colors.blue,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      borderRadius: 8,
                      onTap: () {},
                    ),
                    const SizedBox(height: 30),
                  ],
                ),
              ),
            ),
          ),


          Container(
            padding: EdgeInsets.all(30),
            child: MyButton(
              radius: 10,
              minWidth: double.infinity,
              text: _clickableData,
              onPressed: _clickable ? _goHome : null,
            ),
          ),
        ],
      ),
    );
  }





  Future<void> _goHome() async {

    Navigator.pushNamed(context, "/home");
  }


  // 根据设备类型设置图片和名称
  void _setDeviceInfoByType(int? type) {
    switch (type) {
      case 1:
        _deviceImage = "images/images/add/q1.png";
        _deviceName = '智能摄像机';
        break;
      case 2:
        _deviceImage = "images/images/add/q2.png";
        _deviceName = '智能门铃';
        break;
      case 3:
        _deviceImage = "images/images/add/q3.png";
        _deviceName = '智能门禁机';
        break;
      case 4:
        _deviceImage = "images/images/add/q4.png";
        _deviceName = '智能室内机';
        break;
      default:
        _deviceImage = "images/images/add/q2.png";
        _deviceName = '未知设备';
    }
  }

}


